package com.magima.core.exception;

import com.magima.core.app.ExceptionConstants;
import com.magima.core.app.IExceptionCallback;
import com.magima.core.app.IExceptionManager;

import android.content.Context;
import android.os.Handler;
import android.support.v4.util.LongSparseArray;

public class DefaultExceptionManager implements IExceptionManager{
	private static final long CODE_PLACE_HOLDER = 10000000L;

	private LongSparseArray<IExceptionCallback> roots;
	private Handler mHandler;
	private ExceptionBuilder builder;

	public DefaultExceptionManager(ExceptionBuilder builder){
		roots = new LongSparseArray<IExceptionCallback>();
		mHandler = new Handler();
		this.builder = builder;
	}

	@Override
	public void init(Context context) {
		builder.builder(this, context);
	}

	@Override
	public Handler getHandler(){
		return mHandler;
	}

	@Override
	public void addExceptionCallback(int type, IExceptionCallback callback){

		roots.put(getKey(type, 0), callback);
	}

	@Override
	public void addExceptionCallback(int type, int code, IExceptionCallback callback){
		roots.put(getKey(type,code), callback);
	}

	@Override
	public void removeExceptionCallback(int type){
		roots.delete(getKey(type,0));
	}

	@Override
	public void removeExceptionCallback(int type, int code){
		roots.delete(getKey(type,code));
	}

	@Override
	public IExceptionCallback findByTypeWithoutDefault(int type){
		return findByTypeWithoutDefault(type, 0);
	}

	@Override
	public IExceptionCallback findByTypeWithoutDefault(int type, int code){
		return roots.get(getKey(type, code));
	}

	@Override
	public IExceptionCallback findByType(int type) {
		return findByType(type, 0);
	}

	@Override
	public IExceptionCallback findByType(int type, int code) {
		IExceptionCallback callback = roots.get(getKey(type,code));
		return callback == null ? getDefaultType() : callback;
	}

	@Override
	public IExceptionCallback getDefaultType(){
		return roots.get(getKey(ExceptionConstants.CODE_DEFAULT, 0));
	}

	private static final long getKey(int type, int code ){
		return (long)type*CODE_PLACE_HOLDER+code;
	}
}
